import { todoView } from "./template";
import { addTodo, changeCompletedTodo, removeTodo } from "./todoEvent";
import utils from "./utils";

export interface ITodo {
  id: number,
  content: string,
  completed: boolean
}

@utils
class TodoList {
  private el: HTMLElement;
  private static instance: TodoList;

  constructor(el: HTMLElement) {
    this.el = el;
    // console.log(this.plus(1, 2)); // 3
  }

  public static create(el: HTMLElement) { // 设置单例模式 且避免多次实例化
    if (!TodoList.instance)
      TodoList.instance = new TodoList(el);
    
    return TodoList.instance;
  }

  @addTodo()
  public addItem(todo: ITodo) {
    const oItem: HTMLElement = document.createElement('div');
    oItem.className = 'todo-item';
    oItem.innerHTML += todoView(todo);
    this.el.appendChild(oItem);
  }

  @changeCompletedTodo
  public toggleCompleted(id: number, completed?: boolean) {
    const oItems: HTMLCollection = this.el.getElementsByClassName('todo-item');

    Array.from(oItems).forEach((oItem: HTMLElement) => {
      const _id = parseInt(oItem.querySelector('input').dataset.id);

      if (_id === id) {
        const oContent: HTMLElement = oItem.querySelector('span');
        oContent.style.textDecoration = completed ? 'line-through': 'none';
      }
    });
  }

  @removeTodo
  public removeItem(id: number) {
    const oItems: HTMLCollection = this.el.getElementsByClassName('todo-item');

    Array.from(oItems).forEach((oItem: HTMLElement) => {
      const _id = parseInt(oItem.querySelector('button').dataset.id);

      if (_id === id)
        oItem.remove();
    });
  }
}

export default TodoList;